﻿@using CleanArchitecture.Core.Helper
@using CleanArchitecture.Infrastructure.Entities
@using CleanArchitecture.Infrastructure.Entities.AdminUsers
@using CleanArchitecture.Infrastructure.Entities.Business
@using CleanArchitecture.Infrastructure.Models.Business.Blog
@model BlogItemModel
@{
    Layout = "_BackendLayout";
    ViewData["Title"] = ViewBag.PageTitle as string;
    var AvailableViewer = ViewBag.AvailableViewer as IList<SelectListItem> ?? null;
    var AvailablePublishStyle = ViewBag.AvailablePublishStyle as IList<SelectListItem> ?? null;
    var AvailableLanguages = ViewBag.AvailableLanguages as IList<SelectListItem> ?? null;
    var CurrentUser = ViewBag.CurrentUser as AdminUser ?? null;
    int columntreeType = (int)ViewBag.ColumnTreeType;
}
@section cssstyles {
    <style type="text/css">
        .tox .tox-dialog {
            position: fixed !important;
            top: 30px;
        }

        body {
            margin: 5px !important;
            display: flex;
            flex: auto;
            flex-direction: column;
            min-height: 0;
            background: #f0f2f5;
        }

        .layui-tab-title {
            padding-left: 20px;
        }

        .layui-form-switch {
            margin-top: 6px;
            height: 25px;
        }

        .layui-input-inline {
            width: 320px !important;
        }

        .layui-form-label {
            width: 130px !important;
        }

        .layui-input-block {
            margin-left: 130px !important;
        }

        .layui-slider-input {
            top: 0 !important;
        }

        .levelSlider,
        .orderSlider {
            padding-top: 15px;
        }

        .thumbBox {
            height: 160px;
            overflow: hidden;
            border: 1px solid #e6e6e6;
            border-radius: 2px;
            cursor: pointer;
            position: relative;
            text-align: center;
            line-height: 153px;
        }

        .thumbBox img {
            max-width: 100%;
            max-height: 100%;
            border: none;
        }

        .border {
            border: 1px solid #e6e6e6 !important;
            padding: 10px;
            border-top: none;
        }

        .layui-transfer-active .layui-btn,
        .layui-form-checked[lay-skin=primary] i {
            border-color: #1E9FFF !important;
            background-color: #1E9FFF;
            color: #fff;
        }

        .layui-upload-list {
            overflow: hidden;
        }
        /*在使用float元素的父元素添加overflow:hidden; 解决边框塌陷问题 */
        .layui-upload-list .thumbBox {
            position: relative;
            display: block;
            vertical-align: top;
            padding: 2px 2px;
            border-radius: 5px;
            width: 150px;
            height: 170px;
            float: left;
            margin: 5px;
        }

        .layui-upload-list .thumbBox .picbox {
            display: flex;
            flex: 0 0 auto;
            justify-content: center;
            overflow: hidden;
            position: relative;
            width: 100%;
            height: 150px;
            align-items: center;
        }

        .layui-upload-list .thumbBox .picbox img {
            display: block;
            max-width: 100%;
            max-height: 100%;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translateX(-50%) translateY(-50%);
        }

        .layui-upload-list .thumbBox:hover {
            background-color: #e2e2e2;
        }

        .layui-upload-list .thumbBox .tools {
            display: none;
            position: absolute;
            top: 0;
            right: 0;
            z-index: 99;
            width: 100%;
            height: 100%;
        }

        .layui-upload-list .thumbBox:hover .tools {
            display: block;
        }

        .layui-upload-list .thumbBox .layui-icon {
            font-size: 30px;
        }

        .layui-upload-list .thumbBox .tools .remove {
            cursor: pointer;
            width: 45%;
            float: right;
            padding-top: 50%;
        }

        .layui-upload-list .uploaded i {
            display: block;
        }

        .layui-upload-list i {
            display: none;
            position: absolute;
            color: #01AAED;
            left: 10px;
            bottom: 40%;
            z-index: 1000;
        }

        #videolistpreview .videobox {
            width: 235px;
            height: 265px;
            float: left;
            margin-right: 2%;
            margin-bottom: 15px;
            padding: 6px;
            border-radius: 2px;
            background: #f5f5f5;
            color: #444;
            position: relative;
        }

        #videolistpreview .videobox video {
            width: 100%;
            height: 90%;
        }

        #videolistpreview .videobox .videoplaybtn {
            width: 64px;
            height: 64px;
            background: transparent url(/images/backend/playbtn.png) no-repeat;
            position: absolute;
            left: 50%;
            top: 50%;
            transform: translate(-50%,-50%);
            border: none;
        }

        #videolistpreview .videobox .videoplaybtn.pause {
            background-image: url(/images/backend/pausebtn.png);
        }

        #videolistpreview .videobox h4 {
            font-size: 1em;
            font-weight: bold;
            margin-bottom: 0;
        }

        .layui-btn {
            margin-left: 10px;
        }
    </style>
}
@section csslinks {
    <link rel="stylesheet" type="text/css" href="~/lib/jQueryTagsInput/dist/jquery.tagsinput.min.css" />
}
<div class="layui-main" style="background-color: #fff; width: 100%; padding: 0 20px;">
    <form class="layui-form" action="">
        <div class="layui-tab">
            <ul class="layui-tab-title">
                <li class="layui-this">必填内容</li>
                <li>附件内容</li>
                <li>SEO设置</li>
            </ul>

            <div class="layui-tab-content">
                <!--必填配置-->
                <div class="layui-tab-item layui-show">
                    <!-- 左内容 -->
                    <div class="layui-col-md8 layui-col-xs9" style="padding: 0 10px;">
                        <div class="layui-row layui-col-space10">
                            <div class="layui-col-md9 layui-col-xs7">
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.Title))</label>
                                    <div class="layui-input-block">
                                        <input type="text" class="layui-input" name="@Model.nameof(p => p.Title)" lay-verify="required" placeholder="请输入文章标题" value="@Model.Title" autocomplete="off">
                                    </div>
                                </div>
                                <div class="layui-form-item">
                                    <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.ContentOverView))</label>
                                    <div class="layui-input-block">
                                        <textarea placeholder="请输入内容摘要" name="@Model.nameof(p => p.ContentOverView)" class="layui-textarea">@Model.ContentOverView</textarea>
                                    </div>
                                </div>
                            </div>
                            <div class="layui-col-md3 layui-col-xs3">
                                <div class="thumbBox">
                                    <img class="layui-upload-img" id="coverimage" />
                                    <input class="layui-hide" name="@Model.nameof(p => p.CoverImageUrl)" value="@Model.CoverImageUrl" />
                                </div>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.Contents))</label>
                            <div class="layui-input-block">
                                <textarea name="@Model.nameof(p => p.Contents)" id="@Model.nameof(p => p.Contents)" cols="30" rows="10">@Model.Contents</textarea>
                            </div>
                        </div>
                    </div>
                    <!-- 右内容-->
                    <div class="layui-col-md4 layui-col-xs3">
                        <blockquote class="layui-elem-quote"><i class="fa fa-paper-plane"></i> 基本属性</blockquote>
                        <div class="border">
                            <div class="layui-form-item">
                                <label class="layui-form-label">语言选择</label>
                                <div class="layui-input-block">
                                    <select id="LanguageSelect" asp-items="@AvailableLanguages" lay-filter="LanguageSelect">
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.FKColumnId))</label>
                                <div class="layui-input-block">
                                    <input name="@Model.nameof(m => m.FKColumnId)" type="text" value="@Model.FKColumnId" class="layui-hide" />
                                    <div id="columntreeselect" class="xm-select"></div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.Publisher))</label>
                                <div class="layui-input-block">
                                    <input type="text" class="layui-input" name="@Model.nameof(m => m.Publisher)" value="@Model.Publisher" placeholder="请输入作者" />
                                </div>
                            </div>
                            @*<div class="layui-form-item">
                                    <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.StartTaskTime))</label>
                                    <div class="layui-input-block">
                                        @foreach (var style in AvailablePublishStyle)
                                        {
                                            <input type="radio" name="PublishStyle" title="@style.Text" value="@style.Value" lay-skin="primary" @if (style.Selected) { <text> checked </text> } />
                                        }
                                    </div>
                                </div>
                                <div class="layui-form-item layui-hide releaseDate">
                                    <label class="layui-form-label"></label>
                                    <div class="layui-input-block">
                                        <input type="text" class="layui-input" id="release" placeholder="请选择日期和时间" readonly />
                                    </div>
                                </div>*@

                            <div class="layui-form-item">
                                <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.WhoCanSee))</label>
                                <div class="layui-input-block">
                                    <select asp-for="WhoCanSee" asp-items="@AvailableViewer" lay-verify="required" lay-filter="WhoCanSeeSelect">
                                    </select>
                                    <input name="@Model.nameof(m => m.UserOrRoleId)" value="@Model.UserOrRoleId" class="layui-hide" />
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">内容属性</label>
                                <div class="layui-input-block">
                                    <input type="checkbox" name="@Model.nameof(p => p.IsRecommend)" title="@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.IsRecommend))" lay-skin="primary" lay-filter="IsRecommendCheck" @if (Model.IsRecommend) { <text> checked </text> }>
                                    <input type="checkbox" name="@Model.nameof(p => p.AllowComments)" title="@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.AllowComments))" lay-skin="primary" lay-filter="AllowCommentsCheck" @if (Model.AllowComments) { <text> checked </text> }>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label"><i class="fa fa-sort-amount-asc"></i> @(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.DisplayOrder))</label>
                                <div class="layui-input-block">
                                    <div id="orderSlider" class="orderSlider"></div>
                                    <input type="text" class="layui-hide" name="@Model.nameof(m => m.DisplayOrder)" value="@Model.DisplayOrder" />
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label"><i class="fa fa-tags" aria-hidden="true"></i> @(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.Tags))</label>
                                <div class="layui-input-block">
                                    <textarea name="@Model.nameof(p => p.Tags)" placeholder="请输入标签，最多100个字符，关键字以逗号分隔" class="layui-textarea">@Model.Tags</textarea>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label"><i class="fa fa-clock-o" aria-hidden="true"></i> @(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.UpdatedOnTime))</label>
                                <div class="layui-input-block">
                                    <!-- 注意Linux平台时间转换与windows平台有差异，不再上传时间 即不能加name属性 -->
                                    <input type="text" class="layui-input" value="@Model.UpdatedOnTime" readonly />
                                </div>
                            </div>
                        </div>
                    </div>
                    <div style="width: 100%; height: 50px; line-height: 50px; float: left;"></div> <!--占位符，防止底部固定提交栏遮挡最下层区域-->
                </div>
                <!--附件内容 图片列表等 -->
                <div class="layui-tab-item">
                    <div class="layui-container">
                        <fieldset class="layui-elem-field layui-field-title" style=" margin-top: 30px;">
                            <legend>图片相册</legend>
                        </fieldset>
                        <div class="layui-upload">
                            <button type="button" class="layui-btn layui-btn-normal" id="imglistbtn">上传图片</button>
                            <button type="button" class="layui-btn layui-btn-danger" id="clearimglist">清空列表</button>
                            <input type="text" name="@Model.nameof(m => m.ImageIds)" value="@Model.ImageIds" class="layui-hide" />
                            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                                预览图：
                                <div class="layui-upload-list" id="imglistpreview">
                                </div>
                            </blockquote>
                        </div>
                        <fieldset class="layui-elem-field layui-field-title" style=" margin-top: 30px;">
                            <legend>视频列表</legend>
                        </fieldset>
                        <div class="layui-upload">
                            <button type="button" class="layui-btn layui-btn-normal" id="videolistbtn">选择视频</button>
                            <button type="button" class="layui-btn layui-btn-danger" id="clearvideolist">清空列表</button>
                            <input type="text" name="@Model.nameof(m => m.VideoIds)" value="@Model.VideoIds" class="layui-hide" />
                            <blockquote class="layui-elem-quote layui-quote-nm" style="margin-top: 10px;">
                                预览图：
                                <div class="layui-upload-list" id="videolistpreview">
                                </div>
                            </blockquote>
                        </div>
                    </div>
                </div>
                <!--SEO配置-->
                <div class="layui-tab-item">
                    <div class="layui-row">
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.MetaTitle))</label>
                            <div class="layui-input-inline">
                                <input type="text" name="@Model.nameof(m => m.MetaTitle)" value="@Model.MetaTitle" placeholder="请选输入Seo标题" autocomplete="off" class="layui-input" />
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.MetaKeyWords))</label>
                            <div class="layui-input-inline">
                                @*<input type="text" name="@Model.nameof(m => m.MetaKeyWords)" value="@Model.MetaKeyWords" placeholder="请选输入Seo关键字" autocomplete="off" class="layui-input" />*@
                                <textarea name="@Model.nameof(p => p.MetaKeyWords)" placeholder="请选输入Seo关键字，关键字以逗号分隔" class="layui-textarea">@Model.MetaKeyWords</textarea>
                            </div>
                        </div>
                        <div class="layui-form-item">
                            <label class="layui-form-label">@(ReflectionExtensions.GetPropertyDisplayName<BlogItemModel>(m => m.MetaDescription))</label>
                            <div class="layui-input-inline">
                                <textarea name="@Model.nameof(m => m.MetaDescription)" value="@Model.MetaDescription" placeholder="请输入内容" class="layui-textarea"></textarea>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <input type="text" name="@Model.nameof(m => m.Id)" value="@Model.Id" class="layui-hide" />
        <div class="layui-form-item footerbar">
            <div class="layui-input-block">
                <button class="layui-btn layui-btn-normal" lay-filter="editBlog" lay-submit>
                    <i class="fa fa-paper-plane"></i>发布
                </button>
                <button class="layui-btn layui-btn-primary" id="btnPreview">预览</button>
            </div>
        </div>
    </form>
</div>
@*<button type="button" id="btn_@random" class="layui-hide">tinymceUploaderBtn</button>*@
<!--图片相册模板-->
<script id="imagelistTpl" type="text/html">
    {{#  layui.each(d, function(index, imgobj){ }}
    <div class="thumbBox uploaded">
        <i class="layui-icon layui-icon-upload-drag"></i>
        <div class="picbox">
            <img src="{{imgobj.src}}" data-imageid="{{imgobj.id}}" />
        </div>
        <div class="tools">
            <div class="remove layui-icon layui-icon-delete"></div>
        </div>
    </div>
    {{#  }); }}
</script>

<!--视频列表模板-->
<script id="videolistTpl" type="text/html">
    {{#  layui.each(d, function(index, videoitem){ }}
    <div class="videobox" data-videoid="{{videoitem.id}}">
        <video class="videoplayer">
            <source src="{{videoitem.src}}" />
        </video>
        <button class="videoplaybtn" type="button"></button>
        {{#  if(videoitem.title.length !== 0){ }}
        <h4>{{videoitem.title}}</h4>
        {{#  } }}

    </div>
    {{#  }); }}
</script>

<!--角色选择穿梭框-->
<div class="layui-container layui-hide" id="rolesContainer" style="width: 500px; padding: 10px;"></div>
<input type="text" class="layui-hide" id="columntreeType" value="@columntreeType" />
@section scripts {
    <script src="~/lib/tinymce/tinymce.min.js" asp-append-version="true"></script>
    <script src="~/lib/xm-select/dist/xm-select.js" asp-append-version="true"></script>
    <script src="~/lib/jQueryTagsInput/dist/jquery.tagsinput.min.js"></script>
    <script type="text/javascript">
    $(function () {
        layui.use(['tinymce', 'element', 'notice', 'layer', 'form', 'slider', 'upload', 'laytpl', 'iziToast', 'fileChoose', 'transfer'], function () {
            var tinymce = layui.tinymce,
                form = layui.form,
                layer = layui.layer,
                element = layui.element,
                notice = Util.notice !== null && Util.notice() !== null
                        ? Util.notice() : layui.notice,
                tinymceEditor = null,
                slider = layui.slider,
                uploader = layui.upload,
                laytpl = layui.laytpl,
                iziToast = layui.iziToast,
                fileChoose = layui.fileChoose,
                transfer = layui.transfer,
                lodash = _;

            var loadAdminRoles = function () {
                var index = layer.load(2, { time: 10 * 1000 });
                httpapi.fetchGet('/api/backend/account/getadminroles').then(res => {
                    layer.close(index);
                    if (!httpapi.checkResponse(res)) {
                        //输入信息校验错误
                        notice.error(res.message);
                    }
                    else {//Success
                        transfer.render({
                            elem: '#rolesContainer'
                            , parseData: function (item) {
                                return {
                                    "value": item.Id
                                    , "title": item.RoleName //数据标题
                                    , "disabled": item.disabled
                                    , "checked": item.checked
                                };
                            }
                            , data: res.data
                            , id: "roletrans"
                            , title: ['用户角色列表', '指定用户角色']
                        });
                    }
                }).catch(error => console.error(error));
            };
            var columntreeSelecter = null,
                columntype = $("#columntreeType").val();
                updateColumnTree = function (xmSelector, langid) {
                    var index = layer.load(2, { time: 10 * 1000 });
                    httpapi.fetchGet('/api/backend/business/columnmanage/getcolumntree?languageid=' + langid + "&columntype=" + columntype).then(res => {
                        layer.close(index);
                        if (!httpapi.checkResponse(res)) {
                            //输入信息校验错误
                            notice.error(res.message);
                            xmSelector.update({
                                data: []
                            });
                        }
                        else {//Success
                            if (res.data === null) {
                                notice.error("Empty data!");
                                xmSelector.update({
                                    data: []
                                });
                                return;
                            }
                            xmSelector.update({
                                data() { return res.data; }
                            });
                            var $currentColumn = $("input[name=@Model.nameof(m => m.FKColumnId)]"),
                                initVal = $currentColumn.val();
                            if (typeof initVal === 'string') initVal = parseInt(initVal);
                            var valArr = new Array();
                            valArr.push(initVal);
                            xmSelector.setValue(valArr);
                        }
                    }).catch(error => console.error(error));
                };
            //语言切换选择查询对应ID的栏目菜单
            form.on('select(LanguageSelect)', function(data){
                updateColumnTree(columntreeSelecter, data.value);
            });
            var coverImageUploadIns = null;
            $("#coverimage").on("click", function () {
                let $coverimageUrl = $("input[name=@Model.nameof(m => m.CoverImageUrl)]"),
                    imginfo = [];
                if ($coverimageUrl.val() !== "") {
                    imginfo = lodash.split($coverimageUrl.val(), ';', 2);
                }
                coverImageUploadIns.reload({
                    data: {
                        EntityId: @Model.Id,
                        FileUploadId: imginfo[0],
                        CloudUpload: false,
                        UseCase: "@nameof(UploadUseCategory.BlogCoverImage)"
                    }
                });
            });
            var initPageComponent = function () {
                loadAdminRoles();
                //DavidLee 2020/05/13 Linux平台与window平台对于时间转换有所不同
                //通过 Razor显示的时间数据在Linux平台上无法在Post数据时将时间字符串正确转换为DateTime对象
                //导致数据无法绑定,帮通过Js显示转化时间显示
                @*var editTimeVal = "@Model.UpdatedOnTime";
                var $editTime = $("input[name=@Model.nameof(m => m.UpdatedOnTime)]");
                $editTime.val(util.toDateString(editTimeVal, "yyyy-MM-dd HH:mm"));*@

                tinymceEditor = tinymce.render({
                    elem: "#@Model.nameof(p => p.Contents)",
                    height: 600,
                    file_picker_types: 'file image media',
                    images_upload_handler: function (blobInfo, success, failure) { // 与aximages插件配合使用
                        if (typeof blobInfo !== "undefined") {
                            var formData = new FormData();
                            formData.append("FormData", blobInfo.blob());
                            var uploaddata = {
                                EntityId: @Model.Id,
                                FileUploadId: 0,
                                CloudUpload: blobInfo.cloudupload,
                                UseCase: "@nameof(UploadUseCategory.BlogArticleImage)"
                            };
                            //追加额外的参数
                            layui.each(uploaddata, function (key, value) {
                                value = typeof value === 'function' ? value() : value;
                                formData.append(key, value);
                            });
                            var xhr = new XMLHttpRequest();
                            xhr.withCredentials = false;
                            xhr.open('POST', '/api/backend/business/blogfileupload');
                            xhr.onload = function () {
                                var json;
                                if (xhr.status !== 200) {
                                    console.log('HTTP Error: ' + xhr.status);
                                    failure('HTTP Error: ' + xhr.status);
                                    notice.error("上传失败： Http Error:" + xhr.status);
                                    return;
                                }
                                json = JSON.parse(xhr.responseText);
                                if (!json || json.state !== 200) {
                                    failure(json.message);
                                    notice.error(json.message);
                                    return;
                                }
                                success(json.data.FileUrl);
                            };
                            xhr.send(formData);
                        }
                    },
                    file_picker_callback: function (callback, value, meta) {
                        //meta.filetype: Possible Values: file, image, media
                        //we manually generate the configuration file to ensure that it works fine in virtual directory
                        if (meta.filetype === 'media') {
                            fileChoose.open({
                                fileUrl: '',
                                listUrl: '/api/backend/business/getresourcelist',
                                where: { fileTypes: ["Video"], Page: 1, PageSize: 100 },
                                num: 1,
                                response: {
                                    url: "VirtualUrl",
                                    name: "TitleAttribute",
                                    method: "post"
                                },
                                dialog: {
                                    offset: '60px'
                                },
                                onChoose: function (urls) {
                                    callback(urls[0].VirtualUrl, { alt: urls[0].TitleAttribute });
                                }
                            });
                        }
                    }
                });

                //滑动组件
                let $order = $("input[name=@Model.nameof(m => m.DisplayOrder)]");
                slider.render({
                    elem: '#orderSlider'
                    , min: 1
                    , max: 150
                    , input: true //输入框
                    , theme: '#1E9FFF' //主题色
                    , value: $order.val()
                    , change: function (value) {
                        $order.val(value);
                    }
                });
                //封面图片加载
                let $coverimage = $("#coverimage"),
                    $coverimageUrl = $("input[name=@Model.nameof(m => m.CoverImageUrl)]"),
                    imginfo = [];
                if ($coverimageUrl.val() !== "") {
                    imginfo = lodash.split($coverimageUrl.val(), ';', 2);
                    $coverimage.attr("src", imginfo[1]);
                }
                //封面图片上传事件绑定
                coverImageUploadIns = uploader.render({
                    elem: $coverimage
                    , url: '/api/backend/business/blogfileupload'
                    , accept: 'image'
                    , acceptMime: 'image/*'
                    , field: 'FormData'
                    , data: {
                        EntityId: @Model.Id,
                        FileUploadId: imginfo[0],
                        CloudUpload: false,
                        UseCase: "@nameof(UploadUseCategory.BlogCoverImage)"
                    }
                    ,before: function(obj){
                        layer.load(2, { time: 10 * 1000 });
                    }
                    , done: function (res) {
                        layer.closeAll('loading'); //关闭loading
                        if (res.state && res.state === 200) {
                            notice.success(res.message);
                            $coverimageUrl.val(res.data.FileUploadId + ";" + res.data.FileUrl);
                            $coverimage.attr("src", res.data.FileUrl);
                        }
                        else notice.error(res.message);
                    }
                    , error: function () {
                        layer.closeAll('loading'); //关闭loading
                        notice.error("上传过程失败，请联系系统管理");
                    }
                });
                //栏目选择树
                var langid = $('#LanguageSelect option:selected').val();
                columntreeSelecter = xmSelect.render({
                    el: '#columntreeselect',
                    layVerify: 'required',
                    layVerType: 'msg',
                    autoRow: true,
                    radio: true,
                    clickClose: true,
                    tree: {
                        show: true,
                        showFolderIcon: true,
                        showLine: true,
                        indent: 20,
                        expandedKeys: true,
                        strict: false, //see https://gitee.com/maplemei/xm-select/issues/I15RD1
                    },
                    model: {
                        label: {
                            type: 'block',
                            block: {
                                showCount: 1,//最大显示数量, 0:不限制
                                showIcon: false,//是否显示删除图标
                            }
		                }
	                },
                    theme: {
		                color: '#0081ff',
	                },
                    height: 'auto',
                    data: [],
                    on: function(data){
                        var change = data.change;
                        var selectedColumnId = change[0].value;
                        $("input[name=@Model.nameof(m => m.FKColumnId)]").val(selectedColumnId);
                    }
                });
                updateColumnTree(columntreeSelecter, langid);

                //图片相册初始化
                var $imagelistId = $("input[name='@Model.nameof(m => m.ImageIds)']");
                var imageids = lodash.split($imagelistId.val(), ',');
                var imagesrcs = @(Model.ImageUrls == null
                                                   ? Html.Raw("[]")
                                                   : Html.Raw(Json.Serialize(Model.ImageUrls.ToArray())));
                if (imageids.length > 0 && $imagelistId.val() !== "") {
                    var imageinfoArr = new Array();
                    layui.each(imageids, function (index, item) {
                        imageinfoArr.push({id: item, src: imagesrcs[index]});
                    });
                    var imagelistTpl = document.getElementById("imagelistTpl");
                    var $imagelistContainer = $("#imglistpreview");
                    laytpl(imagelistTpl.innerHTML).render(imageinfoArr, function (html) {
                        $imagelistContainer.append(html);
                    });
                }

                //对图片相册列表删除功能元素进行绑定
                var imagelistbindRemove = function (thumbBox, imagelistId) {
                    if (thumbBox === null) return;
                    thumbBox.on('click', '.remove', function () {
                        layer.confirm('确定删除图片吗？', function (confirmIndex) {
                            var postData = {
                                NewsItemId: @Model.Id,
                                FileIds: thumbBox.find("img").data("imageid"),
                                FileUrls: thumbBox.find("img").attr("src"),
                                IdPropName: "@Model.nameof(m => m.ImageIds)",
                                UrlPropName: "@Model.nameof(m => m.ImageUrls)"
                            };
                            thumbBox.remove();
                            httpapi.fetchPost('/api/backend/business/blogmanage/blogfilelistdelete', postData).then(res => {
                                if (!httpapi.checkResponse(res))
                                    //输入信息校验错误
                                    notice.error(res.message);
                                else {//Success
                                    notice.success(res.message);
                                    //imagelistUrl.val(res.data.NewFileUrls);
                                    //DavidLee 2020/8/7 对新创建文章还未提交编辑更新时，如有删除图片相册操作时，会引起图片Id未保存Bug修复
                                    if (postData.NewsItemId > 0) {
                                        //imagelistUrl.val(res.data.NewFileUrls);
                                        imagelistId.val(res.data.NewFileIds);
                                    } else {
                                        if ($("#imglistpreview .thumbBox").length > 0) {
                                            var $imgs = $("#imglistpreview .thumbBox img");
                                            var remainImgIds = [];
                                            $imgs.each(function () {
                                                remainImgIds.push($(this).data("imageid"));
                                            });
                                            //Or, set the separator with array.join(','); // result: a; b; c.
                                            imagelistId.val(remainImgIds.toString()); // result: a,b,c
                                        }
                                    }
                                }
                            }).catch(error => console.error(error));
                            layer.close(confirmIndex);
                        });
                    });
                };
                $("#imglistpreview .thumbBox").each(function () {
                    imagelistbindRemove($(this), $imagelistId);
                });
                uploader.render({
                    elem: '#imglistbtn'
                    , url: '/api/backend/business/blogfileupload'
                    , multiple: true
                    , accept: 'image'
                    , acceptMime: 'image/*'
                    , field: 'FormData'
                    , data: {
                        EntityId: @Model.Id,
                        FileUploadId: 0,
                        CloudUpload: false,
                        UseCase: "@nameof(UploadUseCategory.BlogCarouselImage)"
                    }
                    ,before: function(obj){
                        iziToast.loading("批量上传中，请稍候...");
                    }
                    , done: function (res) {
                        //上传完毕 与上方图片相册初使化逻辑相同，代码一致，偷懒复制
                        if (res.state !== 200) {
                            notice.error(res.message);
                            return;
                        }
                        //显示图片
                        var imageinfoArr = new Array();
                        imageinfoArr.push({id: res.data.FileUploadId, src: res.data.FileUrl});
                        var imagelistTpl = document.getElementById("imagelistTpl");
                        var $imagelistContainer = $("#imglistpreview");
                        laytpl(imagelistTpl.innerHTML).render(imageinfoArr, function (html) {
                            //动态添加元素绑定追加标识,否则新添加元素无法绑定删除事件
                            var $newupload = $(html);
                            $newupload.addClass("newupload");
                            $imagelistContainer.append($newupload);
                            imagelistbindRemove($imagelistContainer.find(".newupload").last(), $imagelistId);
                        });
                        //回写数据
                        var imageids = $imagelistId.val();
                        //DavidLee 2020/05/06 Bug Repair : 初始化没有相册图片时多增加了分隔符
                        imageids += (imageids.trim().length > 0)
                            ? "," + res.data.FileUploadId
                            : res.data.FileUploadId;
                        //$imagelistUrl.val(imagesrcs);
                        $imagelistId.val(imageids);
                    }
                    , allDone: function (obj) { //当文件全部被提交后，才触发
                        iziToast.destroy();
                        notice.success("上传完成，上传结果：" + obj.successful + "/" + obj.total);
                    }
                });

                // 视频------视频截图 ~~ 视频播放状态 ~~
                const setMedia = function (video) {
                    // 设置poster属性：（非本地视频资源会有跨域截图问题）
                    video.addEventListener('loadeddata', function (e) {
                        // 拿到图片
                        let canvas = document.createElement('canvas');
                        canvas.width = 203;
                        canvas.height = 136;
                        canvas.getContext('2d').drawImage(video, 0, 0, canvas.width, canvas.height);
                        let src = canvas.toDataURL('image/png');
                        // 设置属性
                        video.setAttribute('poster', src);
                    });
                    //检测视频播放状态：
                    //播放按钮
                    let playBtn =  video.parentNode.childNodes[2].nextSibling;
                    //设置状态
                    function videoplaySate(e) {
                        if (video.paused) {
                            video.play();
                            playBtn.classList.add('pause');
                        } else {
                            video.pause();
                            playBtn.classList.remove('pause');
                        }
                    }
                    //点击监听
                    video.addEventListener('click', videoplaySate, false);
                    playBtn.addEventListener('click', videoplaySate, false);
                    //结束监听
                    video.addEventListener('ended',function () {
                        playBtn.classList.remove('pause');
                    });
                };
                var renderVideoList = function (videoitemarr) {
                    var videolistTpl = document.getElementById("videolistTpl");
                    var $videolistContainer = $("#videolistpreview");
                    laytpl(videolistTpl.innerHTML).render(videoitemarr, function (html) {
                        $videobox = $(html);
                        $videolistContainer.append($videobox);
                        $videobox.find("video").each(function () {
                            setMedia(this);
                        });
                    });
                };
                var $videolistId = $("input[name='@Model.nameof(m => m.VideoIds)']");
                //视频列表初始化显示
                if ($videolistId.val() !== "") {
                    var videoidArr = lodash.split($videolistId.val(), ','),
                        videourlArr = @(Model.VideoUrls == null         //lodash.split($videolistUrl.val(), ','),
                                                         ? Html.Raw("[]")
                                                         : Html.Raw(Json.Serialize(Model.VideoUrls.ToArray())));
                        videoitemarr = new Array();
                    layui.each(videoidArr, function (index, item) {
                        videoitemarr.push({ id: item, src: videourlArr[index], title: "" });
                    });
                    renderVideoList(videoitemarr);
                }
                //视频选择
                $('#videolistbtn').click(function () {
                    fileChoose.open({
                        fileUrl: '',
                        listUrl: '/api/backend/business/getresourcelist',
                        where: { fileTypes: ["Video"], Page: 1, PageSize: 100 },
                        num: 2,
                        response: {
                            url: "VirtualUrl",
                            name: "TitleAttribute",
                            method: "post"
                        },
                        dialog: {
                            offset: '60px'
                        },
                        onChoose: function (urls) {
                            var videoitemarr = new Array(),
                                title = "",
                                idstr = "";
                            layui.each(urls, function (index, item) {
                                title = item.TitleAttribute;
                                videoitemarr.push({ id: item.Id, src: item.VirtualUrl, title: title });
                                idstr += item.Id + ",";
                            });
                            renderVideoList(videoitemarr);
                            $videolistId.val(lodash.trimEnd(idstr, ','));
                        }
                    });
                });

                //清空图片视频列表
                $("#clearimglist").on('click', function () {
                    $("#imglistpreview .thumbBox").each(function () {
                        $(this).remove();
                    });
                    $imagelistId.val("");
                });
                $("#clearvideolist").on('click', function () {
                    $("#videolistpreview .videobox").each(function () {
                        $(this).remove();
                    });
                    $videolistId.val("");
                });

                //博客标签输入框
                $("textarea[name=Tags]").each(function () {
                    $(this).tagsInput({
                        'width': 'auto',
                        'height': '120px',
                        'defaultText': '添加',
                        'removeWithBackspace': true,
                        'onAddTag': null
                    });
                });
                $("textarea[name=MetaKeyWords]").each(function () {
                    $(this).tagsInput({
                        'width': 'auto',
                        'height': '120px',
                        'defaultText': '添加',
                        'removeWithBackspace': true,
                        'onAddTag': null
                    });
                });
            };
            initPageComponent();

            form.on('checkbox(IsRecommendCheck)', function (data) {
                $(data.elem).val(data.elem.checked);
            });
            form.on('checkbox(AllowCommentsCheck)', function (data) {
                $(data.elem).val(data.elem.checked);
            });

            //指定用户浏览权限
            form.on('select(WhoCanSeeSelect)', function (data) {
                var $userorroleid = $("input[name=@Model.nameof(m => m.UserOrRoleId)]");
                switch (data.value) {
                    case "@nameof(EntityEnumConfig.WhoCanSee.EveryOne)":
                    case "@nameof(EntityEnumConfig.WhoCanSee.OnlyAdminUser)":
                        $userorroleid.val("");
                        break;
                    case "@nameof(EntityEnumConfig.WhoCanSee.OnlyMe)":
                        $userorroleid.val("@CurrentUser.Id");
                        break;
                    case "@nameof(EntityEnumConfig.WhoCanSee.OnlyAdminRole)":
                        var $roleContainer = $("#rolesContainer");
                        layer.open({
                            type: 1,
                            shade: 0.8,
                            offset: ['100px', '350px'],
                            area: 'auto',
                            shadeClose:true,
                            scrollbar: false,
                            title: "角色选择",
                            content: $roleContainer,
                            btn: ["确定"],
                            success: function (layero, index) {
                                $roleContainer.removeClass("layui-hide");
                            },
                            yes: function (index, layero) {
                                var selectedRoles = transfer.getData('roletrans');
                                var rolestr = "";
                                layui.each(selectedRoles, function (index, item) {
                                    rolestr += item.value + ",";
                                });
                                $userorroleid.val(lodash.trimEnd(rolestr, ','));
                                layer.close(index);
                            },
                            end: function () {
                                $roleContainer.addClass("layui-hide");
                            }
                        });
                        break;
                }
            });

            form.on("submit(editBlog)", function (data) {
                var postJson = data.field;
                if (postJson.IsRecommend === "on") postJson.IsRecommend = true;
                if (postJson.AllowComments === "on") postJson.AllowComments = true;

                if (postJson.hasOwnProperty("select")) { //xm-select
                    delete postJson["select"];
                }
                if (postJson.hasOwnProperty("FormData")) { //image upload
                    delete postJson["FormData"];
                }

                //if (typeof postJson.Contents !== "undefined") {
                postJson.Contents = tinymceEditor.getContent();
                iziToast.loading("编辑提交中，请稍候...");
                httpapi.fetchPost('/api/backend/business/blogmanage/edit', postJson).then(res => {
                    iziToast.destroy();
                    if (!httpapi.checkResponse(res))
                        //输入信息校验错误
                        notice.error(res.message);
                    else {//Success
                        notice.success(res.message);
                        Util.CloseMainWindow();
                    }
                }).catch(error => console.error(error));
                return false;
            });
        });
    });
    </script>
}